import house from '../../../behaviors/house'
import validator from '../../../behaviors/validator'

Page({
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    currentDate: new Date().getTime(),
    maxDate: new Date().getTime() + 86400 * 1000 * 3,
    // houseList: [],
    houseName: '',
    // 表单数据
    houseId: '',
    name: '',
    gender: 1,
    mobile: '',
    visitDate: '',
  },
  behaviors: [house, validator],
  rules: {
    name: [
      { required: true, message: '访客姓名不能为空!' },
      { pattern: /[\u4e00-\u9fa5]{2,5}/, message: '访客姓名只能为中文!' },
    ],
    mobile: [
      { required: true, message: '访客手机号不能为空!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' },
    ],
    houseId: [{ required: true, message: '请选择到访的房屋!' }],
    visitDate: [{ required: true, message: '请选择到访的日期!' }],
  },
  onLoad() {
    this.getHouseList()
  },
  // 获取房屋列表
  // getHouseList() {
  //   wx.http.get('/house').then((res) => {
  //     if (res.code !== 10000) return wx.utils.toast()
  //     this.setData({ houseList: res.data })
  //   })
  // },
  // 用户选择了房屋
  onHouseSelected(ev) {
    const { id: houseId, name: houseName } = ev.detail
    this.setData({ houseId, houseName })
  },
  // 用户选择了日期
  onDateSelcted(ev) {
    const visitDate = wx.utils.dateFormat(ev.detail)
    // 设置访问时间
    this.setData({ visitDate })
    // 关闭popup弹层
    this.closeDateLayer()
  },
  // 提交表单
  submitForm() {
    if (!this.validate()) return
    const { name, gender, mobile, houseId, visitDate } = this.data
    const postData = { name, gender, mobile, houseId, visitDate }
    wx.http.post('/visitor', postData).then((res) => {
      if (res.code !== 10000) return wx.utils.toast('提交访客邀请失败')
      const { id } = res.data
      // 跳转到通行证页面/详情页面
      this.goPassport(id)
    })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  goPassport(id) {
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + id,
    })
  },
})
